const fs = require("fs");
const readVox = require("vox-reader");
const { input } = require('@inquirer/prompts')
const box3ColorBlocks = require("./box3colorblocks.js");

function isNumber(str) {
    return !isNaN(parseFloat(str)) && isFinite(str);
}

(async function () {
    console.log("Box3-vox2blocks-importer v1.0.0 - Box3模型转方块建筑导入工具");
    console.log("Powered By Toby_lai (Tobylai) (@tobylai-toby)")
    console.log("仅支持Box3（Dao3）“Pro”新版本");
    var filename = await input({message:"请输入.vox文件的路径:",validate:(v)=>{
        if(!fs.existsSync(v))return "文件不存在";
        return true;
    }});
    var buf = fs.readFileSync(filename);
    var vox = readVox(buf);
    console.log(`[读取成功] ${filename}`)
    var scale = await input({message:"请输入缩放的倍数[＞0]:",default:0.25,validate:(v)=>{
        if(isNumber(v)){
            if(parseFloat(v)<=0)return "缩放倍数必须大于0";
        }else return "请输入一个有效的数字";
        return true;
    }});;
    var voxelColor = {};// "x,y,z":{r:0,g:0,b:0,a:0} 
    var blocks = {};
    var maxsize = { x: 0, y: 0, z: 0 };
    vox.xyzi.values.forEach((v, index) => {
        if (v.x > maxsize.x) maxsize.x = v.x;
        if (v.y > maxsize.y) maxsize.y = v.y;
        if (v.z > maxsize.z) maxsize.z = v.z;
    })
    var size = {
        x: parseInt(maxsize.x * scale),
        y: parseInt(maxsize.y * scale),
        z: parseInt(maxsize.z * scale)
    }
    vox.xyzi.values.forEach((v, index) => {
        // xzy 方向旋转可以试试三个都试试在前面加上 size.?-
        let pos_str = `${parseInt(v.y * scale)},${parseInt(v.z * scale)},${parseInt(v.x * scale)}`, color = vox.rgba.values[v.i - 1];
        voxelColor[pos_str] = color;
        let voxel_name = box3ColorBlocks.nearestColor(color.r, color.g, color.b);
        // if(voxel_name=="powder_blue"){
        //     voxel_name="blue_glass"
        // }
        //voxel_name = "air";
        blocks[pos_str] = box3ColorBlocks.box3.voxels.id(voxel_name);
    });
    fs.writeFileSync("vox-output.txt", JSON.stringify(blocks));
    console.log("方块数据已经输出到 vox-output.txt");
    console.log("请打开clientside-builder.js获取代码并根据注释使用")
    // console.log(JSON.stringify(blocks))
})();